/* http.js */
// import wxlog from "./log";
import store from '../store/index'
var Fly = require("flyio/dist/npm/wx")
var fly = new Fly
var newFly = new Fly;
var TOKEN = uni.getStorageSync('TOKEN')
var log = console.log
var isLogin = true
function checkSession() {
  return new Promise(function (resolve, reject) {
    uni.checkSession({
      success: () => {
        resolve(true)
        // session_key 未过期，并且在本生命周期一直有效
      },
      fail: () => {
        store.dispatch('wxCodeLogin')
        // session_key 已经失效，需要重新执行登录流程
      }
    });
  })
}
if (TOKEN) {
  checkSession()
}

fly.interceptors.request.use(function (request) {
  if (!TOKEN) {
    //锁定当前实例，后续请求会在拦截器外排队
    fly.lock();

    return store.dispatch('wxCodeLogin').then((res) => {
      TOKEN = res.data.access_token.access_token
      request.headers["Authorization"] = "Bearer " + TOKEN;
      log("token请求成功，值为: " + TOKEN);
      log(`继续完成请求：path:${request.url}，baseURL:${request.baseURL}`)
      return request; //只有最终返回request对象时，原来的请求才会继续
    }).finally(() => {
      fly.unlock();//解锁后，会继续发起请求队列中的任务
    })
  } else {
    request.headers["Authorization"] = "Bearer " + TOKEN;
  }
})

fly.interceptors.response.use(
  function (response) {
    const code = response.data.code
    if (code == 401) {
      if (isLogin) {
        this.lock(); //锁定响应拦截器，
        return store.dispatch('wxCodeLogin')
          .then((res) => {
            TOKEN = res.data.access_token.access_token
            isLogin = false
            log("token已更新，值为: " + TOKEN);
          })
          .finally(() => {
            console.log('解锁队列');
            this.unlock();
          })
          .then(() => {
            log(`重新请求：path:${response.request.url}，baseURL:${response.request.baseURL}`)
            return fly.request(response.request);
          })
      } else {
        return fly.request(response.request);
      }
    } else if (code > 201 || code < 200) {
      uni.showToast({
        title: response.data.msg,
        icon: "none",
        duration: 3000,
      });
    }

    return response;

  },
  function (err) {
    console.log(err);

    uni.showToast({
      title: err.response.data.msg || "系统异常，请稍后再试！",
      icon: "none",
      duration: 3000,
    });
    log("error-interceptor", err)
  }
)
export default class Http {
  static request(method, url, data, headers) {
    return fly.request(url, data, {
      method: method,
      dataType: "json" /* 如设为json，会对返回的数据做一次 JSON.parse */,
      responseType: "text",
      headers: {
        "Content-Type": headers || "application/json;charset=UTF-8",
        Accept: "application/json"
      },
    }).then(res => {
      return res.data
    })
  }
  static postToken(url, data) {
    return newFly.post(url, data).then(res => {
      if (res.data.code != 200) {
        uni.showToast({
          title: res.data.msg,
          icon: "none",
          duration: 3000,
        });
      }
      return res.data
    }).catch(err => {
      uni.showToast({
        title: '系统异常，请稍后再试',
        icon: "none",
        duration: 3000,
      });
      return err
    });
  }
  // 处理 get 请求
  static get(url, data) {
    return this.request("GET", url, data);
  }

  // 处理 post 请求
  static post(url, data, headers) {
    return this.request("POST", url, data, headers);
  }

  // 处理 put 请求
  static put(url, data) {
    return this.request("PUT", url, data);
  }

  // 处理 patch 请求
  static patch(url, data) {
    return this.request("PATCH", url, data);
  }

  // 处理 delete 请求
  static delete(url, data) {
    return this.request("DELETE", url, data);
  }
}
